package com.stox.controller;

import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.stox.dto.web.Response;
import com.stox.manager.ExchangeManager;
import com.stox.model.Exchange;

@RestController
@RequestMapping(value="/exchanges")
public class ExchangeController implements InitializingBean{

	@Autowired
	private ExchangeManager exchangeManager;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		if(0 == exchangeManager.count()){
			Exchange exchange = new Exchange();
			exchange.setId(1l);
			exchange.setCountryId(1l);
			exchange.setName("Bombay Stock Exchange");
			exchangeManager.saveAndFlush(exchange);
		}
	}
	
	@ResponseBody
	@Cacheable(value=ExchangeManager.cacheName, key="'ExchangeController-country-'+#countryId")
	@RequestMapping(method=RequestMethod.GET, produces="application/json")
	public Response<List<Exchange>> findByCountryCode(@RequestParam("countryId") Long countryId){
		return new Response<>(exchangeManager.findByCountryId(countryId)); 
	}
	
}
